package com.wfg.flink.test.redis;

import redis.clients.jedis.Jedis;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class RedisHashValuesExample {
    public static void main(String[] args) {
        // 连接到Redis服务器
        Jedis jedis = new Jedis("localhost", 6379);

        // 假设你的hash的key是"myHash"
        String hashKey = "HASH_NAME";

        // 获取hash中的所有值
        List<String> values = jedis.hvals(hashKey);

        // 使用hgetAll获取哈希中的所有键值对
        Map<String, String> hash = jedis.hgetAll(hashKey);

        String[] headers = { "Name", "counts" };
        String csvFile = "example.csv";
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(csvFile))) {
            // 写入头部
            writeLine(writer, headers);

            // 写入数据
            hash.forEach((k,v)->{
                String[] row = {k,v};
                try {
                    writeLine(writer, row);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            System.out.println("CSV文件已成功创建！");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 关闭连接
        jedis.close();
    }


    private static void writeLine(BufferedWriter writer, String[] values) throws IOException {
        for (int i = 0; i < values.length; i++) {
            writer.write(values[i]);
            if (i < values.length - 1) { // 不是最后一个元素则添加逗号
                writer.write(",");
            }
        }
        writer.newLine(); // 写入新行
    }
}